<?php

class IndexController extends Zend_Controller_Action {

    public function init() {
        
    }

   
    public function indexAction() {
        $auth = Zend_Auth::getInstance();
        $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        try {
            if ($auth->hasIdentity()) {
                $identity = $auth->getIdentity();
                $debugLog->debug("Usuario : " . $identity['username']);
                if ($identity['tipo_usuario'] == VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                    $this->_redirect('/admin/dashboard');
                } else {
                    $this->_redirect('/academico/dashboard');
                }
            }
        } catch (Exception $e) {
            $debugLog->debug($e->getTraceAsString());
        }
    }

    public function loginAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $return = array();
        $login = new VirtualLabs_Login();
        try {
            if ($login->doLogin($this->getRequest()->getParam('username'), $this->getRequest()->getParam('password'))) {
                $return['response'] = 'ok';
                //Obtener datos de usuario
                $userDao = new VirtualLabs_Admin_Usuario();
                $user = $userDao->getUsuario(array('nombre', 'apellido', 'username', 'email', 'tipo_usuario'), array('username' => array('criteria' => '=', 'value' => $this->getRequest()->getParam('username'))));
                $return['tipoUsuario'] = $user['tipo_usuario'];
            } else {
                $return['response'] = 'error';
                $return['message'] = "Usuario y/o Contrasena incorrecta";
            }
        } catch (Exception $e) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($e->getTraceAsString());
            $return ['response'] = 'error';
            $return['message'] = $e->getMessage();
        }
        echo Zend_Json_Encoder::encode($return);
    }

    public function selectAction() {
        
    }

    public function createnewaccountAction() {
        
    }

    /**
     * Metodo invocado por ajax para la creacion de una cuenta nueva
     */
    public function createaccountAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $username = $this->getRequest()->getParam('username');
        $nombre = $this->getRequest()->getParam('nombre');
        $apellido = $this->getRequest()->getParam('apellido');
        $email = $this->getRequest()->getParam('email');
        $password = $this->getRequest()->getParam('password');

        $return = array();
        try {
            //validaciones: Username duplicado y con espacios, Email repetido
            if ($this->validateUsername($username)) {
                $userDao = new VirtualLabs_Admin_Usuario();
                $userDB = $userDao->getUsuario(array('username'), array('username' => array('criteria' => '=', 'value' => $username)));
                if (isset($userDB['username'])) {
                    $return ['response'] = 'error';
                    $return ['message'] = 'El usuario ' . $username . ' ya existe';
                } else {
                    $emailDB = $userDao->getUsuario(array('username'), array('email' => array('criteria' => '=', 'value' => $email)));
                    if (isset($emailDB['username'])) {
                        $return ['response'] = 'error';
                        $return ['message'] = 'La direccion de correo ya existe';
                    } else {
                        //Guardar nueva cuenta del tipo alumno
                        $pass_md5 = VirtualLabs_Admin_Usuario::getPassword($password);
                        $userDao->save(VirtualLabs_Admin_Usuario::TABLE_NAME, array('username' => $username,
                            'nombre' => $nombre,
                            'apellido' => $apellido,
                            'email' => $email,
                            'passw' => $pass_md5,
                            'estado' => 'A',
                            'tipo_usuario' => VirtualLabs_Admin_Usuario::ROL_ALUMNO));
                        $return ['response'] = 'success';
                    }
                }
            } else {
                $return ['response'] = 'error';
                $return ['message'] = 'El nombre de usuario (' . $username . ') no es valido. Se permiten caracteres alfanumericos (en minuscula) y _';
            }
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            $return ['response'] = 'error';
            $return['message'] = $exc->getMessage();
        }
        echo Zend_Json_Encoder::encode($return);
    }

    private function validateUsername($username) {
        return preg_match('/^[a-z0-9_]+$/', $username);
    }

}

